<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>stomp</title>
</head>
<body>

<input id="conn" type="button" value="连接" onclick="connect()">
<input id="disconn" type="button" value="断开连接" disabled="disabled" onclick="disconnected()">
<br>
normal message: <input type="text" id="msg"><input type="button" value="发送" onclick="send()"><br>
announcement：<input type="text" id="msgAnnounce"><input type="button" value="发送" onclick="sendAnnouncement()">

<div id="response"></div>

<script src="jquery-3.3.1.min.js"></script>
<script src="sockjs.js"></script>
<script src="stomp.js"></script>
<script type="application/javascript">
    var stompClient = null;
    function setConnected(connected) {
        document.getElementById("conn").disabled = connected;
        document.getElementById("disconn").disabled = !connected;
        $("#response").html();
    }

    function connect() {
        // var socket = new SockJS("/ws");
        // stompClient = Stomp.over(socket);
        stompClient = Stomp.client('ws://localhost:8080/ws');
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log(frame);

            stompClient.subscribe("/exchange/amq.topic/simp", function (response) {
                $('#response').append("<p>" + response.body + "</p>")
            })

            stompClient.subscribe("/topic/announcement", function (response) {
                $('#response').append("<p>公告: " + response.body + "</p>")
            })

        })
    }

    function send() {
        // 后端设置了, 前缀/app
        stompClient.send("/app/macsimp", {}, "客户端发送的消息..." + $("#msg").val());
        $("#msg").val('')
    }

    function sendAnnouncement() {
        stompClient.send("/app/announcement", {}, "客户端发送的公告..." + $("#msgAnnounce").val());
        $("#msgAnnounce").val('')
    }

    function disconnected() {
        if (stompClient != null) {
            stompClient.disconnect()
        }
        setConnected(false);
        console.log("disconnected");
    }

</script>

</body>
</html>
